package AdvancedEncryptionStandard;

// GF(2^8)，不可约多项式283
public class ByteGF {

    private static final int poly = 283;

    public byte mul(byte mulA, byte mulB) {
        int a = Byte.toUnsignedInt(mulA);
        int b = Byte.toUnsignedInt(mulB);
        int result = 0;
        while (b > 0) {
            if (b % 2 == 1) {
                result = result ^ a;
            }
            a = gmul(a);
            b >>= 1;
        }
        return (byte) (result & 0xff);
    }

    public byte add(byte a, byte b) {
        return (byte) (a ^ b);
    }

    public byte add(byte a, byte b, byte c, byte d) {
        return (byte) (add(a, b) ^ add(c, d));
    }

    // 不可约多项式固定为283
    private int gmul(int a) {
        a <<= 1;
        if ((a & 0x100) == 0x100) {
            a = a ^ poly;
        }

        return a & 0xff;
    }
}
